package com.yeren.jsp.tarena.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yeren.jsp.tarena.dao.EmployeeDAO;
import com.yeren.jsp.tarena.entity.Employee;



public class ActionServlet extends HttpServlet {
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 获取请求资源路径，截取具体动作
		String uri = request.getRequestURI();
		String action = uri.substring(uri.lastIndexOf("/") + 1,uri.lastIndexOf("."));

		// 创建员工管理操作类
		EmployeeDAO dao = new EmployeeDAO();

		// 判断请求动作种类，分不同种类情况处理
		if (action.equals("list")) {// 员工信息列表
			try {
				List<Employee> emps = dao.findAll();
				request.setAttribute("emps", emps);
				request.getRequestDispatcher("listEmp.jsp").forward(request,
						response);
			} catch (Exception e) {
				e.printStackTrace();
				//编程式的处理异常
				request.setAttribute("err_msg", "系统出错，请重试");
				request.getRequestDispatcher("error.jsp").forward(request, response);
			}
		} else if (action.equals("add")) {// 增加员工
			String name = request.getParameter("name");
			double salary = Double.parseDouble(request.getParameter("salary"));
			int age = Integer.parseInt(request.getParameter("age"));
			Employee emp = new Employee();
			emp.setName(name);
			emp.setSalary(salary);
			emp.setAge(age);
			try {
				dao.save(emp);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				//将声明抛给容器，在web.xml中添加声明，编程声明式的处理异常
				throw new ServletException(e);
				
			}
		} else if (action.endsWith("delete")) {// 删除员工
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				dao.delete(id);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (action.endsWith("load")) {// 加载某个员工
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				Employee emp = dao.findById(id);
				request.setAttribute("emp", emp);
				request.getRequestDispatcher("updateEmp.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(action.endsWith("update")){//更新员工
			int id = Integer.parseInt(request.getParameter("id"));
			String name=request.getParameter("name");
			double salary=Double.parseDouble(request.getParameter("salary"));
			int age=Integer.parseInt(request.getParameter("age"));
			Employee emp=new Employee();
			emp.setName(name);
			emp.setSalary(salary);
			emp.setAge(age);
			emp.setId(id);
			try{
				dao.modify(emp);
				response.sendRedirect("list.do");
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

}
